package com.hyh.util;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2019/2/26.
 */

public class CheckHomeUtil {

    private static List<String> names;
    private static ActivityManager mActivityManager;

    public static boolean isAtHome(Context context) {
        if(mActivityManager==null){
            mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        }
        List<ActivityManager.RunningTaskInfo> runningTaskInfos = mActivityManager.getRunningTasks(1);
        return getHomeApplicationList(context).contains(runningTaskInfos.get(0).topActivity.getPackageName());
    }

    private static List<String> getHomeApplicationList(Context context) {
        if(names==null){
            names = new ArrayList<>();
            PackageManager packageManager = context.getPackageManager();
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
            for (ResolveInfo  resolveInfo : resolveInfos) {
                names.add(resolveInfo.activityInfo.packageName);
            }
        }
        return names;
    }
}
